package com.relax.netty.fifthexample;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class MyChatServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        pipeline.addLast(new HttpServerCodec());
        //以块的方式写
        pipeline.addLast(new ChunkedWriteHandler());
        //将多个段聚合起来
        //当浏览器发送大量数据时,会发送多次HTTP请求
        pipeline.addLast(new HttpObjectAggregator(5));
        /**
         * 对websocket的支持
         * 对websocket,数据以帧的形式传递(frame)
         *WebSocketServerProtocolHandler 核心功能是把http协议升级为ws协议,保持长连接
         * 是通过转态码101 升级的
         */
        pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));

        pipeline.addLast(new TestWebSorcrtServerHandler());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
